﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web.Mvc;

namespace Smarly.Core
{
	public class ModelStateObject
	{
		public ModelStateDictionary _modelState = null;
		public ModelStateDictionary ModelState
		{
			get
			{
				if (_modelState == null)
					throw new ApplicationException("Get null ModelState");
				return _modelState;
			}
			set
			{
				if (value == null)
					throw new ApplicationException("Set null ModelState");
				_modelState = value;
			}
		}

		protected void OnSqlInfoMessage(object sender, SqlInfoMessageEventArgs args)
		{
			foreach (var pi in GetType().GetProperties())
			{
				var messageKey = args.Message;
				string propertyName = pi.Name;
				var attrs = pi.GetCustomAttributes(typeof (DatabaseValidationAttribute), true).Cast<DatabaseValidationAttribute>().Where(attr => attr.Key == messageKey).ToList();
				foreach (var a in attrs)
				{
					ModelState.AddModelError(propertyName, a.Message);
					
				}
			}
		}

	}

	public static class ModelStateExtention
	{
		public static Dictionary<string, string> ToErrors(this ModelStateDictionary modelState)
		{
			var pairs = modelState.Where(pair => pair.Value != null && pair.Value.Errors != null && pair.Value.Errors.Count > 0).ToList();
			Dictionary<string, string> result = pairs.Any() ? new Dictionary<string, string>(pairs.Count) : null;
			foreach (var pair in pairs)
			{
				result.Add(pair.Key, pair.Value.Errors.First().ErrorMessage);
			}
			return result;
		}
	}

}